
import { generateUUID } from "./uuid.js"

export function generateEventName(preName = "") {
    return [preName, generateUUID()].join("_")
}

const _observersMap = {}
const _eventNameSplit = "_eventHub"
const _eventNamesCache = {}

function batchOn(events) {
    let ids = []
    events.forEach(({ name, callback }) => {
        let id = on(name, callback)
        ids.push(id)
    })

    return ids
}

function batchOff(ids) {
    if (!Array.isArray(ids)) return
    ids.forEach(id => {
        off(id)
    })
}




export function on(name, fn) {
    if (!fn) return
    if (!_observersMap[name]) {
        _observersMap[name] = []
    }

    let box = _observersMap[name]

    let index = box.findIndex(bfn => bfn === fn)
    if (index === -1) {
        box.push(fn)
        index = box.length - 1
    }

    return [name, index].join(_eventNameSplit)
}

export function off(id) {
    if (!id) return
    let [name, idIndex] = id.split(_eventNameSplit)
    if (!_observersMap[name]) return
    return _observersMap[name].splice(idIndex, 1, null)
}

export function emit(name, ...args) {
    if (!_observersMap[name]) return
    // console.log("[emit]%s", name, args)
    let listens = _observersMap[name]
    listens.forEach(fn => {
        if (typeof fn === "function") {
            fn(...args)
        }
    })
}


export function once(name, fn) {
    let id = on(name, (...args) => {
        off(id)
        typeof fn === "function" && fn(...args)
    })

}


export default {
    emit,
    on,
    off,
    batchOn,
    batchOff,
    generateEventName,
    once
}
